package com.shop.cereshop.business.service.wallet.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.shop.cereshop.business.dao.wallet.CereShopWalletDAO;
import com.shop.cereshop.business.dao.wallet.CereShopWalletTransactionDAO;
import com.shop.cereshop.business.page.wallet.ShopIndexWalletVO;
import com.shop.cereshop.commons.domain.wallet.CereShopWallet;
import com.shop.cereshop.business.service.wallet.CereShopWalletService;

import com.shop.cereshop.commons.domain.wallet.CereShopWalletTransaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 业务实现类
 * 店铺钱包表
 * </p>
 *
 * @author
 */
@Slf4j
@Service
public class CereShopWalletServiceImpl extends ServiceImpl<CereShopWalletDAO, CereShopWallet>
    implements CereShopWalletService {

    @Resource
    private CereShopWalletTransactionDAO cereShopWalletTransactionDAO;

    @Override
    public ShopIndexWalletVO getWallet(Long shopId) {
        ShopIndexWalletVO shopIndexWalletVO = new ShopIndexWalletVO();

        //根据店铺id查询钱包数据
        CereShopWallet shopWallet = lambdaQuery()
                .eq(CereShopWallet::getShopId, shopId)
                .select(CereShopWallet::getBalance, CereShopWallet::getTotalIncome)
                .one();
        if (shopWallet == null) {
            LocalDateTime now = LocalDateTime.now();
            //初始化当前店铺钱包
            CereShopWallet cereShopWallet = CereShopWallet
                    .builder()
                    .shopId(shopId)
                    .balance(BigDecimal.ZERO)
                    .frozenBalance(BigDecimal.ZERO)
                    .totalIncome(BigDecimal.ZERO)
                    .totalWithdrawal(BigDecimal.ZERO)
                    .createTime(now)
                    .updateTime(now)
                    .build();
            //插入钱包数据
            save(cereShopWallet);
            shopIndexWalletVO.setBalance(BigDecimal.ZERO)
                    .setTodayIncome(BigDecimal.ZERO)
                    .setTotalIncome(BigDecimal.ZERO)
                    .setShopId(shopId);
            return shopIndexWalletVO;
        }

        //查询店铺今日收益(需要手续费)
        shopIndexWalletVO = cereShopWalletTransactionDAO.getTodayIncome(shopId);

        shopIndexWalletVO.setBalance(shopWallet.getBalance());
        shopIndexWalletVO.setTotalIncome(shopWallet.getTotalIncome());

        return shopIndexWalletVO;
    }

}
